/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fait.ferm.ui;


import fait.ferm.FermMain;
import fait.ferm.engine.IfaceEngine;
import fait.ferm.engine.ResultEngine;
import fait.ferm.engine.TreeArrItem;
import fait.ferm.global.Glob;
import fait.ferm.persists.SimpleDirItem;
import fait.ferm.tools.Tools;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;


/**
 * Контроллер главного окна.
 * Используется с SceneBuilder
 * @author zx
 */
public class MainFormController  implements Initializable {
//*******************************************************************************	
//                     ПЕРЕМЕННЫЕ ФОРМЫ    
	//меню
	@FXML
	private MenuItem about;
        
        //тулбар
	@FXML
	private Label curDate;
        
        //сплит
//	@FXML
//	private SplitPane split;
	@FXML
	private TreeView<SimpleDirItem> tree;
	@FXML
	private BorderPane rightPane;
	@FXML
	private BorderPane dialogPane;
	@FXML
	private BorderPane dialogPane2;
	@FXML
	private StackPane stackPane;
	@FXML
	private VBox rightBox;
	@FXML
	private HBox statusBar;
	@FXML
	private ScrollPane scrollPane;
	

//*******************************************************************************	
//                     ПЕРЕМЕННЫЕ ЛОГИКИ      
    private IfaceEngine iEngine;
	//private 

        
        
	public TreeView getTree() {
		return tree;
	}

        
        
	public void setTree( TreeItem<SimpleDirItem> root){
		tree.setRoot(root);
		//System.out.println("tree w = ";
		//split.setDividerPositions(0.1);
	}
	
//	/**
//	 *
//	 * @return
//	 */
//	public SplitPane getSplit(){return split;}

	@FXML
	private void handleAboutAction(ActionEvent event) {
		System.out.println("About");
	}
	@FXML
	private void handleExitAction(ActionEvent event) {
		Glob.primaryStage.close();
	}
	@FXML
	private void handleFullScreenAction(ActionEvent event) {
		Glob.primaryStage.setFullScreen(true);
	}
		
	/**
	 *Инициализация главной формы
	 * @param url
	 * @param rb
	 */
	@Override
	public void initialize(URL url, ResourceBundle rb) {
		Glob.dialogPane = dialogPane;
		Glob.dialogPane2 = dialogPane2;
		statusBar.setStyle("-fx-background-color: linear-gradient(to bottom, #efefef 0%, #bfbfbf 100%);-fx-border-width: 1px 0 0 0;-fx-border-color: #006299;");
		//scrollPane.widthProperty()
		

		loadFermOverview();
		final InvalidationListener il = new InvalidationListener() {

			@Override
			public void invalidated(Observable o) {
				TreeItem<SimpleDirItem> t = tree.getSelectionModel().getSelectedItem();
                if(t != null) {
					if(t.getValue().getName().startsWith("Ферма")){
						loadFermOverview();
					}
                     switch(t.getValue().getName()){
                        case "Животные, оборудование":
                            loadPets();
                            break;
                        case "Материалы, молоко":
                            loadSuppliesMilkQuantity();
                            break;
                        case "Персонал":
                            loadStaff();
                            break;
                        case "Управление персоналом":
                            loadStaffManagement();
                            break;
                        case "Кредиты": //кредиты
                            loadCredits();
                            break;
                        case "Текущий план действий": //текущий план
                            loadCurrentPlan();
                            break;
                        case "Договора":
                            loadDogovor();
                            break;
                        default:
                            System.out.println("bum!");
                    }
                }
			}
		};
		tree.setRoot(initCategoryTree());
		tree.getRoot().setExpanded(true);
		for(TreeItem x:tree.getRoot().getChildren()){ x.setExpanded(true);}
		tree.getSelectionModel().selectedItemProperty().addListener(il);
	}

	/**
	 * Получает список элементов дерева категорий главного окна (в левой части окна) из ядра. Возвращает его как
	 * дерево для TreeView.
	 */
	private TreeItem<SimpleDirItem> initCategoryTree(){
		iEngine = Glob.getFermEngine();
		ResultEngine res = iEngine.getMainCategoryTree(Glob.getFerm());
		ArrayList<TreeArrItem> ar=null;
		try {
			ar = res.getArrayListTree();
		} catch (Exception ex) {
			Logger.getLogger(FermMain.class.getName()).log(Level.SEVERE, null, ex);
			Platform.exit();
		}
		ar.get(0).name = Glob.getFerm().name;
		return Tools.arrItem2Tree(ar);
	}        
	
    private void loadPets() {
        try {
				rightPane.getChildren().clear();
				BorderPane p = (BorderPane) FXMLLoader.load(getClass().getResource("PetsTab.fxml"));
				p.managedProperty().set(true);
						
				rightPane.setCenter(p);
				p.prefWidthProperty().bind(rightPane.widthProperty());
                p.prefHeightProperty().bind(rightPane.heightProperty());
				p.widthProperty().addListener(new javafx.beans.value.ChangeListener<Number>(){

					@Override
					public void changed(ObservableValue<? extends Number> ov, Number t, Number t1) {
						System.out.println("old =" + t+ " new = "+t1);
					}

				}); 
				
		} catch (IOException ex) {
			Logger.getLogger(MainFormController.class.getName()).log(Level.SEVERE, null, ex);
		}
    }
    
    private void loadEquipments() {
        try {
				rightPane.getChildren().clear();
				BorderPane p = (BorderPane) FXMLLoader.load(getClass().getResource("EquipmentTab.fxml"));
				p.managedProperty().set(true);
						
				rightPane.setCenter(p);
				p.prefWidthProperty().bind(rightPane.widthProperty());
                p.prefHeightProperty().bind(rightPane.heightProperty());
				p.widthProperty().addListener(new javafx.beans.value.ChangeListener<Number>(){

					@Override
					public void changed(ObservableValue<? extends Number> ov, Number t, Number t1) {
						System.out.println("old =" + t+ " new = "+t1);
					}

				}); 
				
		} catch (IOException ex) {
			Logger.getLogger(MainFormController.class.getName()).log(Level.SEVERE, null, ex);
		}
    }
    
    private void loadStaffManagement() {
        try {
				rightPane.getChildren().clear();
				StackPane p = (StackPane) FXMLLoader.load(getClass().getResource("StaffManagementTab.fxml"));
				p.managedProperty().set(true);
						
				rightPane.setCenter(p);
				p.prefWidthProperty().bind(rightPane.widthProperty());
                p.prefHeightProperty().bind(rightPane.heightProperty());
				p.widthProperty().addListener(new javafx.beans.value.ChangeListener<Number>(){

					@Override
					public void changed(ObservableValue<? extends Number> ov, Number t, Number t1) {
						System.out.println("old =" + t+ " new = "+t1);
					}

				}); 
				
		} catch (IOException ex) {
			Logger.getLogger(MainFormController.class.getName()).log(Level.SEVERE, null, ex);
		}
    }
    
    private void loadStaff() {
        try {
				rightPane.getChildren().clear();
				BorderPane p = (BorderPane) FXMLLoader.load(getClass().getResource("StaffTab.fxml"));
				p.managedProperty().set(true);
						
				rightPane.setCenter(p);
				p.prefWidthProperty().bind(rightPane.widthProperty());
                p.prefHeightProperty().bind(rightPane.heightProperty());
				p.widthProperty().addListener(new javafx.beans.value.ChangeListener<Number>(){

					@Override
					public void changed(ObservableValue<? extends Number> ov, Number t, Number t1) {
						System.out.println("old =" + t+ " new = "+t1);
					}

				}); 
				
		} catch (IOException ex) {
			Logger.getLogger(MainFormController.class.getName()).log(Level.SEVERE, null, ex);
		}
    }
    
    private void loadCredits() {
        try {
				rightPane.getChildren().clear();
				BorderPane p = (BorderPane) FXMLLoader.load(getClass().getResource("CreditTab.fxml"));
				p.managedProperty().set(true);
						
				rightPane.setCenter(p);
				p.prefWidthProperty().bind(rightPane.widthProperty());
                p.prefHeightProperty().bind(rightPane.heightProperty());
				p.widthProperty().addListener(new javafx.beans.value.ChangeListener<Number>(){

					@Override
					public void changed(ObservableValue<? extends Number> ov, Number t, Number t1) {
						System.out.println("old =" + t+ " new = "+t1);
					}

				}); 
				
		} catch (IOException ex) {
			Logger.getLogger(MainFormController.class.getName()).log(Level.SEVERE, null, ex);
		}
    }
	private void loadDogovor(){
		try {
				rightPane.getChildren().clear();
				BorderPane p = (BorderPane) FXMLLoader.load(getClass().getResource("DogovorList.fxml"));
				p.managedProperty().set(true);
						
				rightPane.setCenter(p);
				p.prefWidthProperty().bind(rightPane.widthProperty());
				
		} catch (IOException ex) {
			Logger.getLogger(MainFormController.class.getName()).log(Level.SEVERE, null, ex);
		}
		
	}
    
	private void loadCurrentPlan(){
		try {
				rightPane.getChildren().clear();
				BorderPane p = (BorderPane) FXMLLoader.load(getClass().getResource("PlanTabParentPane.fxml"));
				p.managedProperty().set(true);
						
				rightPane.setCenter(p);
				p.prefWidthProperty().bind(rightPane.widthProperty());
//				p.widthProperty().addListener(new javafx.beans.value.ChangeListener<Number>(){
//
//					@Override
//					public void changed(ObservableValue<? extends Number> ov, Number t, Number t1) {
//						System.out.println("old =" + t+ " new = "+t1);
//					}
//
//				}); 
				
		} catch (IOException ex) {
			Logger.getLogger(MainFormController.class.getName()).log(Level.SEVERE, null, ex);
		}

//		VBox vb = new VBox();
//		TabPane tp = TabPaneBuilder.create()
//					.tabs(
//						TabBuilder.create()
//							.text("Main")
//							.closable(false)
//							.build(),
//						TabBuilder.create()
//							.text("Preview")
//							.closable(false)
//							.build()
//						)
//				   .build();
//		vb.getChildren().add(tp);
//		rightPane.setCenter(vb);
				
	}
	public void loadSuppliesMilkQuantity(){
		try {
			rightPane.getChildren().clear();
			BorderPane p = (BorderPane) FXMLLoader.load(getClass().getResource("SuppliesMilkQuantity.fxml"));
			p.managedProperty().set(true);
			rightPane.setCenter(p);
		} catch (IOException ex) {
			Logger.getLogger(MainFormController.class.getName()).log(Level.SEVERE, null, ex);
		}
		
	}

	public void loadFermOverview(){
		try {
			rightPane.getChildren().clear();
			AnchorPane p = (AnchorPane) FXMLLoader.load(getClass().getResource("FermOverview.fxml"));
			//p.managedProperty().set(true);
			rightPane.setCenter(p);
		} catch (IOException ex) {
			Logger.getLogger(MainFormController.class.getName()).log(Level.SEVERE, null, ex);
		}
	}

}